<template>
  <div class="sign-form-item">
    <Title title="签约信息" style="font-size:16px; margin:10px 0 16px 0"/>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="signRules"
      :label-width="labelWidth"
      class="lineHeight32"
      label-position="right">
      <el-row :class="{'response-create-row': !dialog, 'flex-wrap': dialog}" type="flex">
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="签约所属部门">
            <el-cascader
              v-model="formData.additionalKey.signGroups"
              :show-all-levels="false"
              :options="deptTreeList"
              :props="{
                emitPath:false,
                value: 'id',
                label: 'name',
                checkStrictly: true,
                multiple: false,
              }"
              filterable
              class="width240"
              placeholder="请选择"
              size="small"
            >
              <template slot-scope="{ data }">
                <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
                  <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
                  <span class="inline-tag ellipsisOne">{{ data.name }}</span>
                </el-tooltip>
                <span v-else>{{ data.name }}</span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="达人运营">
            <selectWithUserLoad
              v-model="formData.additionalKey.operatorId"
              :hide-select-list="formData.additionalKey.operator || []"
              :style="{ 'width': showMobilePage ? 'auto' : '240px' }"
              :clearable="true"
              :multiple="true"
              placeholder="请选择人员"
              key-name="id"
              label-name="userName"
              filterable
              @changeMethod="updateFollowUsers($event, 'operatorId', 'operator')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="执行经纪">
            <selectWithUserLoad
              v-model="formData.additionalKey.executeBrokerId"
              :hide-select-list="formData.additionalKey.executeBroker || []"
              :style="{ 'width': showMobilePage ? 'auto' : '240px' }"
              placeholder="请选择人员"
              key-name="id"
              multiple
              label-name="userName"
              filterable
              clearable
              @changeMethod="updateFollowUsers($event, 'executeBrokerId', 'executeBroker')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" :class="{'label-collapse-global': isSigned}" class="responsive-col-lg-8">
          <el-form-item label="现维护经纪人" prop="followContractBrokerId">
            <selectWithUserLoad
              v-model="formData.additionalKey.followContractBrokerId"
              :hide-select-list="formData.additionalKey.followContractBroker || []"
              :style="{ 'width': showMobilePage ? 'auto' : '240px' }"
              placeholder="请选择人员"
              key-name="id"
              multiple
              label-name="userName"
              filterable
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="工作微信" prop="workWxCode">
            <el-input v-model="formData.additionalKey.workWxCode" :maxlength="100" class="width240" placeholder="请输入工作微信" type="text" size="small" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="签约有效期" prop="signDate">
            <el-date-picker
              v-model="formData.additionalKey.signDate"
              :disabled="hasLinkLegal"
              type="daterange"
              align="right"
              size="small"
              class="width240"
              value-format="timestamp"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy/MM/dd" />
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="试合作期" prop="cooperationTime" class="rel">
            <el-date-picker
              v-model="formData.additionalKey.cooperationTime"
              type="monthrange"
              align="right"
              size="small"
              class="width240"
              value-format="timestamp"
              unlink-panels
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy/MM" />
            <div class="month">
              <span v-if="formData.additionalKey.cooperationTime && formData.additionalKey.cooperationTime.length">
                {{ getMonth(formData.additionalKey.cooperationTime[0], formData.additionalKey.cooperationTime[1])+'个月' }}
              </span>
              <span v-else>--</span>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="合作方式" prop="cooperationOption">
            <selectWithoutHttp v-model="formData.additionalKey.cooperationOption" :list-data="cooperationOption" clearable class="width240" key-name="value" label-name="label"/>
          </el-form-item>
        </el-col>
        <el-col v-if="isJournalPlatform && !isWeiBo" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item label="返点比例" prop="pointHighestRatio">
            <div class="cost-item">
              <el-input
                v-model="formData.additionalKey.pointHighestRatio"
                oninput="if(value>100)value=100;if(value<0)value=0;"
                placeholder="请输入比例"
                class="width240"
                type="number"
                size="small"
                @change="numberInputChange('pointHighestRatio')"
                @mousewheel.native.prevent
              >
                <span slot="suffix" class="suffix">%</span>
              </el-input>
            </div>
          </el-form-item>
        </el-col>
        <!-- 3.4.4把原对接信息的自定义字段放到了签约信息里面 -->
        <!-- 动态字段 -->
        <el-col v-for="(item) in formData.handoverKey.dynamicKey" :key="item.name" :span="rowSpan" class="responsive-col-lg-8">
          <el-form-item :prop="item.name" class="dynamicKey-label">
            <el-tooltip slot="label" :content="item.name" placement="top" effect="dark">
              <div class="item ellipsisOne">
                {{ item.name }}
              </div>
            </el-tooltip>
            <dynamicKey :item="item"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import upAttachment from '@/components/Common/upAttachment/index';
import { hasRouteAuth } from '@/utils/permission';
import { getDepartmentAll } from '@/api/config';
import mixins from './mixins';
import { mapState } from 'vuex';
import { cooperationOption } from '@/utils/accountCommonData';
import { getMonth } from '@/views/resource/create/resourceData';
export default {
  components: { selectWithUserLoad, selectWithoutHttp, upAttachment },
  mixins: [mixins],
  model: {
    prop: 'modelData',
    event: 'changeValue'
  },
  props: {
    modelData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    rowSpan: {
      type: Number,
      default: 12
    },
    isSigned: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      cooperationOption,
      deptTreeList: [],
      showRelatedContract: false,
      autoRenewalOptions: [{ id: 0, label: '否' }, { id: 1, label: '是' }]
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    hasLinkLegal() {
      return !!(this.formData.additionalKey.signLegal && this.formData.additionalKey.signLegal.id);
    },
    wxPlatform() {
      return ['微信视频号', '微信'].includes(this.modelData.platformTypeName);
    },
    signRules() {
      const validateArr = (msg, item) => {
        return (rule, value, callback) => {
          if (item && item.length) {
            callback();
          } else {
            callback(new Error(msg));
          }
        };
      };
      const validateType = (msg, item) => {
        return (rule, value, callback) => {
          if (item || item === 0) {
            callback();
          } else {
            callback(new Error(msg));
          }
        };
      };
      const rules = {};
      if (this.isSigned) { // 现维护经纪人仅已签约账号必填
        rules['followContractBrokerId'] = [{ required: true, trigger: 'change', validator: validateArr('请选择现维护经纪人', this.formData.additionalKey.followContractBrokerId) }];
      }
      if (this.wxPlatform || this.kuaiShou) {
        rules['cooperationOption'] = [{ required: true, trigger: 'change', validator: validateType('请选择合作方式', this.formData.additionalKey.cooperationOption) }];
      }
      if (this.isJournalPlatform && !this.isWeiBo) {
        rules['pointHighestRatio'] = [{ required: true, trigger: 'blur', validator: validateType('请选择返点比例', this.formData.additionalKey.pointHighestRatio) }];
      }
      return this.isJournalPlatform ? { ...rules, ...this.formRules } : this.formRules;
    }
  },
  created() {
    this.queryDeptTreeList();
  },
  methods: {
    getMonth,
    hasRouteAuth,
    // 获取部门
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
      }).catch(e => {
        console.log(e);
      });
    },
    numberInputChange(key) {
      if (this.formData.additionalKey[key]) this.formData.additionalKey[key] = Number(this.formData.additionalKey[key]).toFixed(2);
    },
    updateFollowUsers(list, key, appendKey) { // 执行经纪/达人运营新增人员，资源信息【跟进人】字段需要同步添加
      const allUserIds = _.cloneDeep(this.formData.additionalKey[key]) || [];
      const users = _.cloneDeep(this.formData.additionalKey[appendKey]) || [];
      const appendList = (list || []).filter(i => users.every(user => user.id !== i.id));
      appendList.forEach(user => {
        users.push({ id: user.id, userName: user.userName });
      });
      const currUser = users.filter(user => allUserIds.includes(user.id));
      this.$emit('updateFollowUsers', currUser);
    }
  }
};
</script>

<style lang="scss" scoped>
// .sign-form-item {

// }
.width240 {
  width: 240px;
  &::v-deep {
    .el-select {
      width: 240px;
    }
    .el-input__inner {
      width: 240px;
    }
  }
}
.legal-code-container {
  display: flex;
  align-items: center;
  width: 240px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  &.legal-code-container-mobile {
    width: auto;
  }
  .icon {
    font-size: 14px;
    color: #ccc;
    cursor: pointer;
    margin-right: 8px;
    display: none;
  }
  &:hover {
    .icon {
      display:block;
    }
  }
}
.legal-code {
  color: #333;
  height: 32px;
  padding: 0 8px;
  line-height: 32px;
  flex:1;
  cursor: pointer;
  &.placeholder {
    color: #bbb;
  }
}
.title {
  font-size: 16px;
  font-weight: 600;
  text-align: left;
  color: #333333;
  line-height: 16px;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  .dot {
    width: 4px;
    height: 4px;
    background-color: #406EFF;
    margin-right: 6px;
  }
}
.month {
  position: absolute;
  left: 250px;
  top: 0;
}
.mock-input {
  &::v-deep {
    .el-input-number__increase,.el-input-number__decrease {
      display: none;
    }
    .el-input__inner {
      text-align: left;
      padding-left: 8px;
    }
  }
}
</style>
